package db

import (
	"time"

	"code_gen/logger"
	"gorm.io/gorm"
	l "gorm.io/gorm/logger"
	"moul.io/zapgorm2"
)

func CreateDB(dialector gorm.Dialector) (*gorm.DB, error) {

	// 适配zap的logger
	lg := zapgorm2.New(logger.Log.Desugar())
	lg.LogLevel = l.Info
	lg.SlowThreshold = 200 * time.Millisecond

	db, err := gorm.Open(dialector, &gorm.Config{Logger: lg})
	if err != nil {
		return nil, err
	}

	sqlDb, err := db.DB()
	if err != nil {
		return nil, err
	}

	sqlDb.SetConnMaxLifetime(time.Hour)
	sqlDb.SetMaxOpenConns(5)
	sqlDb.SetMaxIdleConns(1)
	sqlDb.SetConnMaxIdleTime(time.Hour)

	return db, err
}
